/**
 * Copyright 2011 Honeywell Federal Manufacturing & Technologies, LLC. This material was produced under U.S. Government
 * contract DE-ACO4-01AL66850, Honeywell Federal Manufacturing & Technologies, LLC, (FM&T) with the U. S. Department of
 * Energy for the operation of the Kansas City Plant . The U.S. Government has rights to use, reproduce, and distribute
 * this software.  NEITHER THE GOVERNMENT NOR Honeywell Federal Manufacturing & Technologies, LLC, MAKES ANY WARRANTY,
 * EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.  If software is modified to produce
 * derivative works, such modified software should be clearly marked, so as not to confuse it with the version available
 * from FM&T.
 *
 * Additionally, this program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License Version 3 published by the Free Software Foundation. Accordingly, this program is distributed in
 * the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this library.
 * If not, see http://www.gnu.org/licenses/.
 */
package org.braintrain.tapestry.view;

import com.javaforge.tapestry.spring.annotations.InjectSpring;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.InjectObject;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.services.DataSqueezer;
import org.braintrain.domain.Content;
import org.braintrain.domain.ContentBase;
import org.braintrain.domain.Navigation;
import org.braintrain.domain.ResourceFacade;
import org.braintrain.domain.types.ResourceType;
import org.braintrain.services.DeltaResourceManager;
import org.braintrain.services.MediaService;
import org.braintrain.services.util.contentBaseVisitor.ContentBaseVisitorResolvingExtractor;
import org.braintrain.tapestry.aso.EditingASO;
import org.braintrain.tapestry.view.components.TinyMCEConfigurationFactory;

import javax.servlet.ServletContext;

/**
 * Tapestry View page.  This page displays the Content associated with a navigation.  This
 * page also allows the ContentCreators to edit and create new content through TinyMCE.
 * 
 * @author John Ericksen
 *
 */
public abstract class View extends BrainTrainEditableNavigatablePage
{
    @InjectSpring("mediaService")
    public abstract MediaService getMediaService();
    
    @InjectObject("service:tapestry.data.DataSqueezer")
    public abstract DataSqueezer getDataSqueezer();

    @InjectSpring("resourceManager")
    public abstract DeltaResourceManager getResourceManager();
    
    @InjectState("editingaso")
    public abstract EditingASO getEditingASO();
    
    public abstract String getCurrentEditedContent();
    public abstract void setCurrentEditedContent(String c);
    
    @Persist("session:page")
    public abstract boolean isEditContent();
    public abstract void setEditContent(boolean editContent);

    @InjectObject("service:tapestry.globals.ServletContext")
    public abstract ServletContext getServletContext();

    /**
     * Returns the current content.  if the page is rewinding, copy off an editable
     * version of the content to allow for editing
     *
     * @return
     */
    public Content getCurrentContent(){
        return getEditingASO().getEditable(Content.class, getEditableKey(), getRequestCycle().isRewinding() && isDeltaUser(), produceNewEditable());
    }
    
    /**
     * Initialize the page
     */
    public void init(){
        Content currentContent;

        if(isDeltaUser()){
            currentContent = produceNewEditable();
        }
        else{
            currentContent = (Content) getNavigation().getContent(false);
        }

        setEditableKey(getEditingASO().checkinEditable(currentContent));
    }

    private Content produceNewEditable(){

        ContentBase content;
        if(getNavigation().getContent().getDeltaValue() == null){
            content = getNavigation().getContent().getValue().copy();
        }
        else{
            content = getNavigation().getContent().getDeltaValue();
        }
        ContentBaseVisitorResolvingExtractor extractor = new ContentBaseVisitorResolvingExtractor();
        content.accept(extractor);
        return extractor.getContent();
    }
    
    /**
     * Get the current content as a string
     * @param content
     */
    public void setContent(String content)
    {
        setCurrentEditedContent(content);
    }
    
    public String getContent()
    {
        return getResourceManager().getResourceValue(((Content)getNavigation().getContent(isDeltaUser())).getContent());
    }

    public TinyMCEConfigurationFactory getConfigurationFactory(){
        TinyMCEConfigurationFactory factory = new TinyMCEConfigurationFactory();

        factory.addConfiguration("plugins", factory.getConfigurationValue("plugins") + ",popupLink,pageLink");
        factory.addConfiguration("theme_advanced_buttons2", addLinkPlugins(factory.getConfigurationValue("theme_advanced_buttons2")));
        factory.addConfiguration("page_link_chooser_callback", "braintrainLinkChooser");
        factory.addConfiguration("popup_link_chooser_callback", "braintrainPopupChooser");

        return factory;
    }

    private String addLinkPlugins(String buttons) {

        int linkIndex = buttons.indexOf("anchor,");

        if(linkIndex == -1){
            linkIndex = 0;
        }

        return buttons.substring(0, linkIndex) +
        "popupLink,pageLink," +
        buttons.substring(linkIndex);
    }

    /**
     * Save and continue editing
     */
    public void saveSubmit(IRequestCycle cycle)
    {
        Navigation currentNav = getNavigation();
        if(currentNav != null)
        {
            Content current = getCurrentContent();

            if(getCurrentEditedContent() != null)
            {

                if(current.getContent() == null){
                    current.setContent(new ResourceFacade(ResourceType.Content));
                }

                String content = getContentService().parseHTMLBlobFile(getCurrentEditedContent(), current.getContent(), getNavId(), true, currentNav.isMainNavigation(), getDataSqueezer());
                getResourceManager().saveResourceValue(content, current.getContent());

                currentNav.getContent().setDeltaValue(current);

                currentNav.setName(current.getName());
                currentNav.setPending(true);
                getGenericService().saveOrUpdate(currentNav);
            }
            
            setEditContent(true);
            
            init();
        }
    }
    
    /**
     * Turn on the editing mode
     * @param cycle
     */
    public void editContentSubmit(IRequestCycle cycle)
    {
        Object[] params = cycle.getListenerParameters();
        if(params != null && params.length > 0 && params[0] instanceof Long)
        {
            setNavId((Long)params[0]);
            if(params.length > 1 && params[1] instanceof Long)
            {
                setParentNavId((Long)params[1]);
            }
            init();
        }
    }
    
    public static String dotdot(String in, int end)
    {
        if(in.length() > end)
        {
            return in.substring(0, end) + "..";
        }
        return in;
    }
}
